<?php

namespace App\Logics\Admin\Ucenter;

use App\Commons\Domain\Module\Exchange\Model\Order;
use App\Commons\Domain\Module\Financial\Model\Wallet;
use App\Commons\Domain\Module\UserCenter\Contract\AccountService;
use App\Commons\Domain\Module\UserCenter\Model\Member;
use Arr;

/**
 *
 * @authors generator
 * @date    2020-11-09 09:37:57
 */
class MemberLogic
{
    // TODO:
    /**
     * 会员列表
     * @param array $param [description]
     * @return [type]        [description]
     */
    function memberList(array $param)
    {
        $size = Arr::pull($param, 'size');
        $where = [];
        $or_where = [];
        if ($status = Arr::pull($param, 'status')) {
            $where[] = ['disabled_at'];
        }
        $or_where += collect($param)->filter()
            ->map(fn($item, $key) => [$key, 'like', "%{$item}%", 'or'])
            ->values()->toArray();

        return app(AccountService::class)->paginateMember(compact('where', 'or_where', 'size'));
    }

    public function memberInfo(string $uid)
    {
        return Member::whereUid($uid)->firstOrFail();
    }

    public function memberWallet(string $uid)
    {
        return Wallet::whereUid($uid)->get();
    }

    public function memberTrade(array $params)
    {
        return Order::with('advertising:id,uid')
            ->whereTraderUid($params['uid'])
            ->whenFilled(
                Arr::get($params, 'start_time'),
                Arr::get($params, 'end_time'),
                function ($query, $create_time_start, $create_time_end) {
                    $query->where(
                        [
                            ['create_at', '>=', $create_time_start],
                            ['put_at', '<=', $create_time_end]
                        ]
                    );
                }
            )
            ->when(
                Arr::get($params, 'type'),
                function ($query, $type) {
                    $query->whereHas(
                        'advertising',
                        function ($user_query) use ($type) {
                            $user_query->whereType($type);
                        }
                    );
                }
            )
            ->when(
                Arr::get($params, 'coin'),
                function ($query, $coin) {
                    $query->whereHas(
                        'advertising',
                        function ($user_query) use ($coin) {
                            $user_query->CoinId($coin);
                        }
                    );
                }
            )
            ->latest('id')
            ->paginate();

    }
}
